package com.androidtests;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;


public class AndroidSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
	
	private static final String TAG = AndroidSurfaceView.class.getSimpleName();
	
	private AndroidThread androidThread;
	private String avgFps;
      
	public AndroidSurfaceView(Context context) {
        super(context);
        getHolder().addCallback(this);
        androidThread = new AndroidThread(getHolder(), this);
    }
	
	public void setAvgFps(String avgFps) {
	    this.avgFps = avgFps;
	}
	 
	private void displayFps(Canvas canvas, String fps) {
	    if (canvas != null && fps != null) {
	        Paint paint = new Paint();
	        paint.setARGB(255, 255, 255, 255);
	        canvas.drawText(fps, this.getWidth() - 50, 20, paint);
	    }
	}

 
    @Override
    public void onDraw(Canvas canvas) {
        Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
        canvas.drawColor(Color.BLACK);
        canvas.drawBitmap(icon, 10, 10, null);
        
        displayFps(canvas, avgFps);
    }

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		androidThread.setRunning(true);
		androidThread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		boolean retry = true;
		androidThread.setRunning(false);
        while (retry) {
            try {
            	androidThread.join();
                retry = false;
            } catch (InterruptedException e) {
                // we will try it again and again...
            }
        }
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			if (event.getX() > 400) {
				androidThread.setRunning(false);
				((Activity)getContext()).finish();
			} else {
				Log.d(TAG, "Coords: x=" + event.getX() + ",y=" + event.getY());
			}
		}
		return super.onTouchEvent(event);
	}
}
